<?php
namespace app\v2\controller;
use think\Db;
use think\Request,
    app\v2\model\ScoreLog;



class TonDun extends Base
{
    protected $options = array();
    protected $user = array();

    public function __construct()
    {
        parent::__construct();
        $this->user = session('user');
        $this->TondunModel =  model('v2/Tondun');
        $this->systemConfigModel =  model('common/SystemConfig');
        $this->Score =  model('v2/Score');
        if('127.0.0.1' == $_SERVER['SERVER_ADDR'] ){
            DEFINE('IS_TEST',true);
        }else{
            DEFINE('IS_TEST',false);
        }

        $this->status = array('-5'=>'欠费','-1'=>'删除','0'=>'禁止显示','1'=>'正常','2'=>'套餐过期','3'=>'订单超过上限','4'=>'下架');
        // var_dump(IS_TEST);die;
        // echo json_encode($_SERVER['SERVER_ADDR']);die;
        //测试
        // $this->user['uid'] = '5C83DAE7';
    }


    public function tdCheck(){

        // 准备接口参数
        $data = array(
            "partner_code" => "qhwd",
            "secret_key" => "66f2bc1432c44823953de3551e26ef72",
            "event_id" => "loan_professional_web",
            "token_id" => "qhwd_".session_id(),//此处填写设备指纹服务的会话标识，和部署设备脚本的token一致
            // "account_login" => "2694279546@qq.com",
            // "ip_address" => get_client_ip(),
            // "people" =>'{"account_email":["893939741@qq.com"],"id_number":"370404199006301915","account_name":"皮晴晴","account_phone":["15961718173"],"account_mobile":["15961718173"]}'
        );

        $info = array();
        $info['account_name'] = '皮晴晴';
        $info['card_number'] = '6230901807030310952';
        $info['id_number'] = '370404199006301915';
        $info['account_mobile'] = '15961718173';
        $info['qq_number'] = '893939741';
        $info['account_email'] = '893939741@qq.com';
        // echo json_encode($data);die;
        // 调用接口
        $data = array_merge($data,$info);
        $result = invoke_fraud_api($data);
        echo json_encode($result);die;
    }

    /**
     * 风险决策 - 规则详情
     * @author llj <llj465705075@gmail.com>
     * @time(2016年12月11日22:15:39)
     */
    public function doRuleDatail(){

        // 调用接口
        $sequence_id = '1480841287662884F0B5612C34096523';
        $result = rule_detail($sequence_id  );

        echo json_encode($result);die;


    }


    /**
     * 贷前申请 - 页面
     * @author llj <llj465705075@gmail.com>
     * @time(2016年12月11日22:16:04)
     */
    public function preloanCheck()
    {
        $arr=$this->isLogin();
        if(!$arr['status']){
            return resultArray(['error' =>$arr['info']]);
        }
        //$uid = '1131';//测试
        $uid=$arr['uid'];
        $data = Db::name('td_account')->field('total_times')->where('uid',$uid)->find();
        //获取系统配置单价
        $res=$this->systemConfigModel->getSysConfigList();
        if($res['CREDIT_UNIT_PRICE']<1){
            $data['price']=10;
        }else{
            $data['price']=$res['CREDIT_UNIT_PRICE'];
        }
        if(!$data){
            $data['total_times']=0;     //历史查询次数
        }
        //获取用户余额
        $data['score']=$this->Score->balance($uid);
        return resultArray(['data' => $data]);
    }
    /**
     * 贷前申请 - 提交资料
     * @author llj <llj465705075@gmail.com>
     * @time(2016年12月11日22:16:31)
     */
    public function doPreloanCheck(Request $request){
       $arr=$this->isLogin();
        if(!$arr['status']){
            return resultArray(['error' =>$arr['info']]);
        }
        $uid=$arr['uid'];
        //自动获取表单数据 并进行验证
        $datas=$request->post();

        $data1=$this->TondunModel->checkCredit($datas,$uid);
        //如果不存在则证明表单验证失败
        if(!$data1) return resultArray(['error' => $this->TondunModel->getError()]);
        $accountdata=array();
        //判断是否第一次查询免费  查的到就不是第一次
        $isfrist=Db::name('td_account')->where('uid',$uid)->find();
        if($isfrist['first_times']){
            //不是第一次 查单价扣钱
            // $res=$this->systemConfigModel->getSysConfigList();
            // if($res['CREDIT_UNIT_PRICE']<1){
            //     $score=10;
            // }else{
            //     $score=$res['CREDIT_UNIT_PRICE'];
            // }
            $accountdata["last_time"] = time();
            $accountdata["last_time_str"] = date('Y-m-d H:i:s',time());
            if($isfrist['total_times'] > 5){  // 定义查询最大次数为5次
              return resultArray(['error'=>'查询次数过多']);
            }
            $accountdata['total_times']=$isfrist['total_times']+1;
            $score=0;  //查询报告扣的金额  第一次免费
        }else{
            $score=0;  //查询报告扣的金额  第一次免费
            $accountdata['uid']=$uid;
            $accountdata["create_time"] = time();
            $accountdata["create_time_str"] = date('Y-m-d H:i:s',time());
            $accountdata["last_time"] = time();
            $accountdata["last_time_str"] = date('Y-m-d H:i:s',time());
            $accountdata['total_times']=1;
            $accountdata['first_times']=1;
        }
       //获取用户余额
        // $ye=$this->Score->balance($uid);
        // if($ye<$score){
        //     return resultArray(['error' =>'账户余额不足,请先充值!']);
        // }
        /* 调用 [贷前审核] 接口 返回一个状态和一个申请风险报告编号  IS_TEST判断是否式本地数据*/
        $result = preloan_apply($data1,IS_TEST);
        if( $result['success']){
            $data['name'] = $data1['name'];
            $data['id_number'] = $data1['id_number'];
            $data['mobile'] = $data1['mobile'];
            $data['report_id'] = $result['report_id'];
            $data['uid'] = $uid;
            $data['is_test'] = IS_TEST;
            $data["create_time"] = time();
            $data["create_time_str"] = date('Y-m-d H:i:s',time());
            //注  这个可以用strict(true)
            //$id = Db::name('td_preloan_apply')->strict(true)->insert($data);
        //扣钱成功之后 将数据存入查询记录中  要跳到记录中看报告
            $add=array();
            $add["report_id"] = $result['report_id'];
            $add["uniacid"] = 2;
            $add['is_test'] = IS_TEST;
            $add['uid'] = $uid;
            $add["create_time"] = time();
            $add["create_time_str"] = date('Y-m-d H:i:s',time());
       //开启事务
       Db::startTrans();
         try {
          //扣钱扣钱
             // $this->Score->handle($uid,$score,$opreation="setDec");
             //echo $re1.'<br1>';
          //用户提交详情表
             Db::name('td_preloan_apply')->insert($data);
          //扣钱成功后  往统计加数据
             if($isfrist){
              Db::name('td_account')->where('uid',$uid)->update($accountdata);
             }else{
              Db::name('td_account')->insert($accountdata);
             }

         //把记录添加到用户历史审核记录表里
            Db::name('td_preloan_report')->insert($add);

         #写日志
         $scoreLogModel = new ScoreLog();
         $scoreLogModel->addlog($uid,$recored=0,$score,$opretion="setDec",$logid=1,$type="查征信");
           Db::commit();
           return resultArray(['data'=>$result['report_id']]);
         } catch(\Exception $e) {
           Db::rollback();
           return resultArray(['error'=>'查询失败，请稍后重试！']);
         }
        }else{
            return resultArray(['error' => $result['reason_desc']]);
        }

    }



    /**
     * 贷前申请 - 查询报告详情
     * @author llj <llj465705075@gmail.com>
     * @time(2016年12月11日22:16:04)
     * http://local.yifu.com/cvi.php?s=/tong_dun/report/report_id/ER2016121123314012494030.html
     */
    public function report(Request $request)
    {
        $arr=$this->isLogin();
        //$this->user['uid'] = '5C83DAE7';//测试
        //$uid='5C83DAE7';
        $param['uid']=$arr['uid'];
        $param['report_id']=$request->post("report_id","");

        $result=$this->TondunModel->detail($param);
      if(!$result){
          return resultArray(['error' => $this->TondunModel->getError()]);
      }
      /*  var_dump($result);
        exit();*/
         return resultArray(['data' => $result]);

    }

   /*历史审核记录*/
    public function history(){
        $arr=$this->isLogin();
        if(!$arr['status']){
            return resultArray(['error' =>$arr['info']]);
        }
        $uid=$arr['uid'];
        

        //条件
        $where = array();
        $where['a.uid'] = $uid;

        //排序
        $order = '';
        $order .= 'a.id desc';
        //查询
        $report_list = $this->TondunModel->lists(array('td_preloan_report'), $where,$order,array(),'a.status,a.id,a.uid,a.is_test,a.create_time_str,a.report_id,a.application_id,a.final_score,a.final_decision,p.name');
        return resultArray(['data' => $report_list]);
    }


   //刷新列表页  主要是改变报告可否查看状态
    public function refresh (Request $request){
        //判断是否登陆
       $arr=$this->isLogin();
        if(!$arr['status']){
            return resultArray(['error' =>$arr['info']]);
        }
        $param['uid']=$arr['uid'];
        // $param['uid']=125;
        $param['report_id']=$request->post("report_id","");
        $re=$this->TondunModel->refresh($param);
        if(!$re){
            return resultArray(['error' => $this->TondunModel->getError()]);
        }else{
            return resultArray(['data' => $re]);
        }
    }


}